import json

from django.http import JsonResponse
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views.decorators.http import require_POST
from django.views.generic import ListView, DetailView, DeleteView
from django.shortcuts import get_object_or_404
from django.shortcuts import redirect
from loguru import logger
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response

from django_filters.rest_framework import DjangoFilterBackend

from apps.cases.serializers import *
from apps.cases.models.case import *
from apps.cases.pagination import CasesPagination
from utils.cases_runner import TestRunner


def create_case(request):
    if request.method == "POST":
        # 这里处理表单提交逻辑
        # 示例：Case.objects.create(...)
        return redirect("cases_home")  # 创建成功后跳转回列表页
    return render(request, "cases/case_create_new.html")  # 渲染创建页模板


def case_edit_view(request, case_id):
    case = get_object_or_404(CaseModel, id=case_id)
    context = {"case": case, "protocol_choices": ["HTTP", "Thrift", "SQL"]}  # 示例数据
    return render(request, "cases/cases_edit.html", context)


class CaseView(ListView):
    """测试用例 homepage"""

    model = CaseModel
    template_name = "cases/home.html"
    context_object_name = "case_list"
    ordering = "-create_time"
    paginate_by = 8

    def get_queryset(self):
        # TODO: 缺少按照产品过滤测试用例 + 授权的用例
        return CaseModel.objects.filter().all()


class CaseDetails(DetailView):
    model = CaseModel
    template_name = "cases/cases_detail.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        return context


# 测试用例视图
class CaseViewSet(viewsets.ModelViewSet):
    queryset = CaseModel.objects.prefetch_related("cases_step").all()
    serializer_class = CaseSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ["product", "status", "name"]
    # 分页
    pagination_class = CasesPagination

    @action(detail=True, methods=["post"])
    def execute(self, request, pk=None):
        """执行测试用例"""
        case = self.get_object()
        result = TestRunner(case).execute()
        return Response(result)

    # @action(detail=False, methods=['post'])
    # def create_case(self, request):
    #     """创建测试用例"""
    #     logger.info('create test case')
    #     serializer = self.get_serializer(data=request.data)
    #     logger.debug('case data >>> {data}', data = serializer)
    #     if not serializer.is_valid():
    #         return Response(serializer.errors, status=400)
    #     serializer.is_valid(raise_exception=True)
    #     case = serializer.save()
    #
    #     return Response({
    #         'id': case.id,
    #         'message': '用例创建成功'
    #     }, status=201)

    def create(self, request, *args, **kwargs):
        """创建测试用例"""
        logger.info("create test case")
        logger.debug("request data >>> {data}", data=request.data)
        return super().create(request, *args, **kwargs)


# 步骤操作视图
class CaseStepViewSet(viewsets.ModelViewSet):
    serializer_class = CaseStepSerializer

    def get_queryset(self):
        return CaseStep.objects.filter(case_id=self.kwargs["case_pk"])

    def perform_create(self, serializer):
        case = get_object_or_404(CaseModel, pk=self.kwargs["case_pk"])
        serializer.save(case=case)


class CaseBulkDeleteView(DeleteView):
    """删除测试用例"""

    model = CaseModel  # 替换为你的实际模型
    http_method_names = ["post"]  # 仅允许POST请求
    success_url = "/"  # 删除成功后跳转地址（AJAX模式下可不使用）

    def post(self, request, *args, **kwargs):
        """
        处理POST请求的删除操作
        请求格式示例：
        {
            "operation": "delete",  # 操作类型
            "case_ids": [1,2,3]     # 要删除的ID列表
        }
        """
        try:
            # 解析JSON请求体
            data = json.loads(request.body)
            operation = data.get("operation")

            if operation != "delete":
                return JsonResponse({"status": "error", "message": "无效操作"}, status=400)

            case_ids = data.get("case_ids", [])
            if not isinstance(case_ids, list) or len(case_ids) == 0:
                return JsonResponse(
                    {"status": "error", "message": "无效的用例ID列表"}, status=400
                )

            # 获取安全查询集并进行删除
            queryset = self.get_queryset().filter(id__in=case_ids)
            deleted_count, _ = queryset.delete()

            return JsonResponse(
                {
                    "status": "success",
                    "deleted_count": deleted_count,
                    "details": list(queryset.values_list("id", flat=True)),
                }
            )

        except json.JSONDecodeError:
            logger.error("JSON decoding error >>> {}", request.body)
            return JsonResponse({"status": "error", "message": "无效的JSON格式"}, status=400)

        except Exception as e:
            logger.error("Delete case error >>> {}", str(e))
            return JsonResponse({"status": "error", "message": str(e)}, status=500)

    def get_queryset(self):
        """安全查询集（示例：限制为当前用户的用例）"""
        return (
            super()
            .get_queryset()
            .filter(
                owner=self.request.user,
            )
        )
